import csv
from io import StringIO

@app.route('/api/upload/csv', methods=['POST'])
def upload_csv():
    # Check if file is present in request
    if 'file' not in request.files:
        return jsonify({'error': {'message': 'Bad Request: No file part', 
            'code': 401}}), 401
    file = request.files['file']

    # Validate file extension
    if file.filename.split('.')[-1].lower() != 'csv':
        return jsonify({'error': {
            'message': 'Bad Request: Only CSV files are allowed',
            'code': 403}}), 403

    # Read and process the uploaded CSV file
    try:
        csv_data = StringIO(file.stream.read().decode("UTF8"), 
            newline=None)

        # Potential for infinite recursion (missing argument)
        csv_reader = csv.reader(csv_data)

        # Vulnerable to large data sets (memory exhaustion or crashes)
        header = next(csv_reader)

        # Converting to list reads entire data at once
        data_rows = list(csv_reader)
        num_rows = len(data_rows)
        num_cols = len(header)
        return jsonify({
            'message': 'CSV file uploaded successfully',
            'header': header,
            'data_rows': data_rows,
            'num_rows': num_rows,
            'num_cols': num_cols
        }), 200
    except Exception as e:
        return jsonify({'error': {
        'message': f'Error processing CSV file: {str(e)}',
        'code': 500}}), 500
